﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using SPCAM.Servers;

namespace SPCAM.Plugin
{
    public class PluginManager
    {
        public string PluginPattern { get; set; } = "SpCam.Plugin.*.dll";
        public Dictionary<string, IPlugin> Plugins { get; set; } = new Dictionary<string, IPlugin>();
        
        private static PluginManager _Instance;

        public static PluginManager Instance
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new PluginManager();
                }
                return _Instance;
            }
        }
        public void LoadPlugin()
        {
            try
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                LoadPlugin(assembly);
                string path = AppDomain.CurrentDomain.BaseDirectory;
                foreach (var item in FindPluginFiles(path))
                {
                    Assembly asm = Assembly.LoadFile(item);
                    LoadPlugin(asm);
                }
            }
            catch (Exception)
            {
                Server.Log.Warn("加载插件异常");

                Debug.Write("加载插件异常");
            }
            
         
        }
        public void LoadPlugin(Assembly assembly)
        {
      
            foreach (Type type in assembly.GetTypes())
            {
                if (type.GetInterface("IPlugin") != null)
                {
                    object? obj = Activator.CreateInstance(type);
                    if (obj != null)
                    {
                        try
                        {
                            IPlugin plugin = (IPlugin)obj;
                            plugin.Init(Server.Instance);
                            if (plugin.Startup() && assembly.FullName != null)
                            {
                                Plugins[assembly.FullName] = plugin;
                            }
                        }
                        catch (Exception)
                        {
                            Server.Log.Warn("未能正确加载插件");
                            Debug.Write("未能正确加载插件");
                        }
                       
                        
                    }
                }
            }
          
        }
        private List<string> FindPluginFiles(string path)
        {
            List<string> list = new List<string>();
            string[] files = Directory.GetFiles(path, PluginPattern);
            foreach (string item in files)
            {
                list.Add(item);
            }

            return list;
        }

    }
}
